<template>
  <Card dis-hover :bordered="false">
    <Form inline :label-width="0" @submit.native.prevent>
      <Row>
        <Col span="22">
          <FormItem>
            <Input
              placeholder="请输入手机号或备注信息"
              v-model="params.keywords"
              @on-clear="searchData"
              @on-enter="searchData"
              clearable
            />
          </FormItem>
          <FormItem>
            <Select
              v-width="150"
              placeholder="请选择项目"
              v-model="params.project_id"
              :filterable="projectlist.length >= 10"
              @on-open-change="showAll"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in projectlist"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <Select
              v-width="150"
              placeholder="认证人"
              ref="select"
              v-model="params.authenticator_user"
              :filterable="authenticatorlist.length >= 10"
              @on-open-change="showAll"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in authenticatorlist"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem>
            <TreeSelect
              v-width="150"
              placeholder="部门"
              v-model="params.department_id"
              :data="departmentList"
              @on-change="searchData"
              @on-clear="clearDep"
              clearable
            />
          </FormItem>
          <FormItem v-if="usernameList.length > 0">
            <Select
              v-width="150"
              placeholder="使用人"
              ref="select"
              v-model="params.use_mid"
              :filterable="usernameList.length >= 10"
              @on-open-change="showAll"
              @on-change="searchData"
              clearable
            >
              <Option
                v-for="item in usernameList"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
        </Col>
        <Col span="2" style="text-align: right">
          <Button
            type="primary"
            @click="handleAdd"
            v-hasC="{
              name: 'v1-buss-scard-update-scard',
              flag: 'v1/buss/scard/update-scard',
            }"
            class="ivu-ml-8"
            >新增</Button
          >
        </Col>
      </Row>
    </Form>
    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      :max-height="tableHeigth"
    >
      <template #action="{ row }">
        <a
          @click="handleTopup(row)"
          v-hasC="{
            name: 'v1-buss-scard-recharge-list',
            flag: 'v1/buss/scard/recharge-list',
          }"
          >话费记录</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-scard-recharge-list',
            flag: 'v1/buss/scard/recharge-list',
          }"
        />
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-buss-scard-update-scard2',
            flag: 'v1/buss/scard/update-scard',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-buss-scard-update-scard2',
            flag: 'v1/buss/scard/update-scard',
          }"
        />
        <a
          @click="handleDel(row.id)"
          class="del"
          v-hasC="{
            name: 'v1-buss-scard-delete-scard',
            flag: 'v1/buss/scard/delete-scard',
          }"
          >删除</a
        >
      </template>
      <template #status="{ row }">
        <Badge
          status="success"
          :text="row.status_name"
          v-if="row.status === '1'"
        />
        <Badge status="error" :text="row.status_name" v-else />
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form ref="create" :model="scardInfo" :rules="rules" :label-width="80">
        <FormItem
          label="手机卡号"
          prop="sim_card"
          :rules="{
            required: true,
            message: '请输入正确的联系号码',
            pattern: /^1\d{9,10}$/,
            trigger: 'blur',
          }"
        >
          <Input
            v-model="scardInfo.sim_card"
            placeholder="请输入手机号"
            type="tel"
            @input="scardInfo.sim_card = scardInfo.sim_card.slice(0, 11)"
          />
        </FormItem>

        <FormItem label="所属项目" prop="project_id" required>
          <Select
            v-model="scardInfo.project_id"
            placeholder="请选择项目"
            :filterable="projectAddList.length >= 10"
            @on-open-change="showAll"
            @on-change="getUser"
            clearable
          >
            <Option
              v-for="item in projectAddList"
              :value="item.value + ''"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="所属部门" prop="department_id" required>
          <TreeSelect
            style="width: 100%"
            placeholder="请选择部门"
            v-model="scardInfo.department_id"
            :data="departmentAddList"
            @on-change="getUser"
          />
        </FormItem>
        <FormItem label="运营商" prop="sim_telecom" required>
          <Select
            v-model="scardInfo.sim_telecom"
            placeholder="请选择运营商"
            :filterable="operatorAddList.length >= 10"
            @on-open-change="showAll"
            clearable
          >
            <Option
              v-for="item in operatorAddList"
              :value="item.value + ''"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="认证人" prop="authenticator_user" required>
          <dropdown
            :searchVal="scardInfo.authenticator_user"
            @changeVal="changeVal"
            :isNeedSearch="true"
            :placeholder="placeholder"
            :itemlist="userAddList"
          ></dropdown>
        </FormItem>
        <FormItem label="使用人" prop="use_mid">
          <Select
            v-model="scardInfo.use_mid"
            placeholder="请选择使用人"
            :filterable="usernameAddList.length >= 10"
            @on-open-change="showAll"
            clearable
          >
            <Option
              v-for="item in usernameAddList"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input
            v-model="scardInfo.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="4"
          />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="scardInfo.status" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="addModal = false">取消</Button>
        <Button
          type="primary"
          @click="ok"
          :loading="btnloading"
          class="ivu-ml-8"
          >保存</Button
        >
      </div>
    </Modal>

    <topup
      ref="topUp"
      :id="currentId"
      :showTopup="showTopup"
      @closeTopup="closeTopup"
    />
  </Card>
</template>
<script>
import topup from "./topup";
import Dropdown from "@/components/searchinput";
import {
  scardList,
  createScard,
  deleteScard,
  scardCondition,
  getMemberCondition,
} from "@api/phonecard.js";
export default {
  name: "phonecard",
  components: { topup, Dropdown },
  data() {
    return {
      placeholder: "请输入认证人",
      tableHeigth: document.body.clientHeight - 280,
      addModal: false,
      showTopup: false,
      currentId: "",
      edit: true,
      loading: false,
      btnloading: false,
      total: 0,
      pageOpts: [10, 20, 30, 40],
      params: {
        keywords: "",
        project_id: "",
        authenticator_user: "",
        status: "",
        use_mid: "",
        department_id: "",
        current: 1,
        size: 10,
      },
      projectlist: [], //项目下拉
      authenticatorlist: [], //认证人下拉
      departmentList: [],
      operatorAddList: [],
      projectAddList: [],
      userAddList: [],
      usernameList: [],
      usernameAddList: [],
      departmentAddList: [],
      columns: [
        {
          key: "id",
          title: "ID",
          width: 80,
        },
        {
          key: "sim_card",
          title: "手机卡号",
          width: 125,
        },
        {
          key: "project_name",
          title: "所属项目",
          width: 110,
        },
        {
          key: "sim_telecom_name",
          title: "运营商",
          width: 100,
        },
        {
          key: "devices_name",
          title: "当前设备",
          ellipsis: "true",
          tooltip: "true",
          minWidth: 140,
        },
        {
          key: "authenticator_user",
          title: "认证人",
          width: 100,
        },
        {
          key: "use_mname",
          title: "使用人",
          width: 100,
        },
        {
          key: "department_name",
          title: "部门",
          width: 180,
        },
        {
          slot: "status",
          title: "状态",
          width: 80,
        },
        {
          key: "remark",
          title: "备注",
          ellipsis: "true",
          tooltip: "true",
          minWidth: 140,
        },
        {
          slot: "action",
          title: "操作",
          width: 185,
          fixed: "right",
        },
      ],
      list: [],
      scardInfo: {
        id: "",
        sim_card: "",
        project_id: null,
        sim_telecom: "",
        authenticator_user: "",
        use_mid: null,
        remark: "",
        department_id: null,
        status: true,
      },
      rules: {
        project_id: [{ required: true, message: "请选择项目" }],
        department_id: [{ required: true, message: "请选择部门" }],
        sim_telecom: [{ required: true, message: "请选择运营商" }],
        authenticator_user: [{ required: true, message: "请选择认证人" }],
      },
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    showAll(e) {
      if (e) {
        let downList = document.querySelectorAll(
          ".ivu-select-dropdown-list .ivu-select-item"
        );
        downList.forEach((item) => {
          item.style.display = "block";
        });
      }
    },
    changeData(data) {
      data.forEach((item) => {
        item.value = +item.id;
        item.title = item.department_name;
        item.expand = true;
        if (item.children && item.children.length > 0) {
          this.changeData(item.children);
        }
      });
      return data;
    },
    changeVal(e) {
      this.scardInfo.authenticator_user = e;
    },
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          deleteScard({ id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    handleAdd() {
      scardCondition({ id: 0 }).then((res) => {
        this.scardInfo = {
          id: "",
          sim_card: "",
          project_id: null,
          department_id: null,
          sim_telecom: "",
          authenticator_user: "",
          use_mid: null,
          remark: "",
          status: true,
        };
        this.operatorAddList = res.condition.sim_telecoms_arr;
        this.projectAddList = res.condition.project_arr;
        this.userAddList = res.condition.authenticator_arr;
        this.departmentAddList = this.changeData(res.condition.department_arr);
        this.$nextTick(() => {
          this.$refs.create.resetFields();
        });
      });

      this.addModal = true;
      this.edit = true;
    },
    handleEdit(info) {
      this.addModal = true;
      this.edit = false;
      this.$refs.create.resetFields();
      scardCondition({ id: info.id }).then((res) => {
        this.operatorAddList = res.condition.sim_telecoms_arr;
        this.projectAddList = res.condition.project_arr;
        this.userAddList = res.condition.authenticator_arr;
        this.departmentAddList = this.changeData(res.condition.department_arr);
        this.$nextTick(() => {
          this.scardInfo = {
            id: info.id,
            sim_card: info.sim_card,
            project_id: info.project_id,
            department_id: +info.department_id ? +info.department_id : null,
            sim_telecom: info.sim_telecom,
            authenticator_user: info.authenticator_user,
            use_mid: info.use_mid ? +info.use_mid : null,
            remark: info.remark,
            status: info.status == "1" ? true : false,
          };
          this.getUser();
        });
      });
    },

    handleTopup(e) {
      this.showTopup = true;
      this.currentId = e.id;
    },
    closeTopup(state) {
      this.showTopup = state;
    },
    getData() {
      this.loading = true;
      const params = {
        keywords: this.params.keywords,
        project_id: this.params.project_id,
        authenticator_user: this.params.authenticator_user,
        status: this.params.status,
        use_mid: this.params.use_mid,
        department_id: this.params.department_id,
        pageSize: this.params.size,
        page: this.params.current,
      };
      scardList(params)
        .then((res) => {
          this.projectlist = res.condition.project_arr;
          this.authenticatorlist = [...res.condition.authenticator_arr];
          this.usernameList = res.condition.use_member_arr;
          this.departmentList = this.changeData(res.condition.department_arr);
          this.list = res.list;
          this.total = res.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    searchData() {
      this.params.current = 1;
      this.getData();
    },
    clearDep() {
      this.params.department_id = "";
      this.searchData();
    },
    handleCreate2(val) {
      this.userAddList.push({
        value: val,
        label: val,
      });
    },
    findUser(id) {
      return this.usernameAddList.findIndex((item) => {
        return item.value == id;
      });
    },
    getUser() {
      getMemberCondition({
        project_id: this.scardInfo.project_id,
        department_id: this.scardInfo.department_id,
      }).then((res) => {
        this.usernameAddList = res;
        if (this.findUser(this.scardInfo.use_mid) == -1) {
          this.scardInfo.use_mid = null;
        }
      });
    },
    addPatient() {
      this.btnloading = true;
      const params = {
        project_id: this.scardInfo.project_id,
        department_id: this.scardInfo.department_id,
        sim_card: this.scardInfo.sim_card,
        sim_telecom: this.scardInfo.sim_telecom,
        authenticator_user: this.scardInfo.authenticator_user,
        use_mid: this.scardInfo.use_mid,
        remark: this.scardInfo.remark,
        status: this.scardInfo.status ? 1 : 0,
      };
      if (this.edit) {
        createScard(params)
          .then((res) => {
            this.$Message.success("新增成功");
            this.btnloading = false;
            this.addModal = false;
            this.getData();
          })
          .catch(() => {
            this.btnloading = false;
          });
      } else {
        createScard(Object.assign({}, params, { id: this.scardInfo.id }))
          .then((res) => {
            this.$Message.success("编辑成功");
            this.btnloading = false;
            this.addModal = false;
            this.getData();
          })
          .catch(() => {
            this.btnloading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addPatient();
        } else {
          this.addModal = true;
          // this.$Message.error('填写错误，保存失败！')
          return;
        }
      });
    },
  },
};
</script>
